from django.http import JsonResponse
from backend.cews.models import RepairOrderRepairDetails
from drf_spectacular.utils import extend_schema, inline_serializer
from rest_framework import serializers
from rest_framework import status as ResponseStatus
from rest_framework.decorators import action
from rest_framework.mixins import (CreateModelMixin, ListModelMixin,
                                   RetrieveModelMixin, UpdateModelMixin)
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from backend.gnsuser.models import GnsUser
from utils.autoschema import AutoDocSchema, custom_response_serailizer
from utils.decorators import error_response, request_data
from backend.gnsuser.api.GnsUserSerializer import GnsUserSerializer
from backend.gnsuser import services

class GnsUserViewSet(
    # RetrieveModelMixin,
    # ListModelMixin,
    # UpdateModelMixin,
    GenericViewSet,
    # CreateModelMixin
):

    serializer_class = GnsUserSerializer
    queryset = GnsUser.objects.all()

    @action(detail=False, methods=['post'], schema=AutoDocSchema(),
            url_path='check-username', url_name='check-username')
    @request_data(keys=['username','check_state'])
    @error_response()
    def check_username(self,request,username,check_state):
        username_base64 = username
        
        gnsuser = GnsUser.objects.filter(qrcode=username_base64).first()

        if not gnsuser or gnsuser.user.is_active == False:
            return JsonResponse({
                'err':'Username not found',
                'ack':False
            })

        if gnsuser:
            user = gnsuser.user
        
        if user:
            
            checkFunction = services.getCheckFunction(check_state)

            if not checkFunction:
                return JsonResponse({
                    'err':'Incorrect check_state',
                    'ack':False
                })

            has_permission = checkFunction(user)

            if has_permission:
                return JsonResponse({
                    'user_id':user.id,
                    'username_base64':username_base64,
                    'username':user.username,
                    'ack':True
                })
                
            else:
                return JsonResponse({
                    'err':'User has insufficient permission',
                    'ack':False
                })

        return JsonResponse({
            'err':'Username not found',
            'ack':False
        })